BaseTabContainer.componentDidMount   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
/* global window */
2
import React from 'react';
3
import PropTypes from 'prop-types';
4
5
import { Tabs, Tab } from 'react-bootstrap';
6
7
export default class BaseTabContainer extends React.Component {
8
  constructor(props, configs = []) {
9
    super(props);
10
11
    this.configs = configs;
12
    this.state = {
13
      activeTab: window.location.hash ? window.location.hash.substr(1) : this.configs[0].eventKey,
14
    };
15
    this.tabs = {};
16
  }
17
18
  componentDidMount() {
19
    this.refreshTab();
20
    window.addEventListener('hashchange', () => {
21
      const activeTab = (window.location.hash) ? window.location.hash.substr(1) : this.configs[0].eventKey;
22
      this.onTabChanged(activeTab);
23
    });
24
  }
25
26
  onTabChanged(activeTab) {
27
    this.setState({ activeTab }, () => this.refreshTab());
28
    window.location.hash = `#${activeTab}`;
29
  }
30
31
  refreshTab() {
32
    this.tabs[this.state.activeTab].refresh();
33
  }
34
35
  renderTabs() {
36
    const tabConfigs = this.configs;
37
    const inheritProps = Object.assign({}, this.props);
38
    delete inheritProps.id;
39
40
    return tabConfigs.map(tab => (
41
      <Tab eventKey={tab.eventKey} title={tab.title}>
42
        {React.createElement(
43
          tab.ChildComponent,
44
          Object.assign({
45
            ref: (elem) => { this.tabs[tab.eventKey] = elem; },
46
          }, inheritProps),
47
        )}
48
      </Tab>
49
    ));
50
  }
51
52
  render() {
53
    return (
54
      <Tabs id={this.props.id} activeKey={this.state.activeTab} onSelect={t => this.onTabChanged(t)}>
55
        {this.renderTabs()}
56
      </Tabs>
57
    );
58
  }
59
}
60
61
BaseTabContainer.propTypes = {
62
  id: PropTypes.string.isRequired,
63
};
64